const app = getApp()
const Utils = require('../../utils/util.js')

// pages/index/index.js.js
Page({
  data: {
    // used to store user info like portrait & nickname
    userInfo: {},
    hasUserInfo: false,
    // whether to disable join btn or not
    disableJoin: false
  },
  onLoad: function (options) {
    // wx.showLoading({ title: '正在加载' })
    this.channel = "1000";
    this.uid = Utils.getUid();
    this.lock = false;
    let userInfo = wx.getStorageSync("userInfo");
    if (userInfo){
      this.setData({
        hasUserInfo: true,
        userInfo: userInfo
      });
    }
  },
  onReady: function () {
  },
  onShareAppMessage() {
  },
  onHide: function () {
  },
  onUnload: function () {
  },
  onGotUserInfo: function(e){
    let userInfo = e.detail.userInfo || {};
    wx.setStorage({
      key: 'userInfo',
      data: userInfo,
    })
    this.onJoin(userInfo);
  },
  checkJoinLock: function() {
    return !(this.lock || false);
  },
  lockJoin: function() {
    this.lock = true;
  },
  unlockJoin: function() {
    this.lock = false;
  },
  onJoin: function (userInfo) {
    userInfo = userInfo || {};
    let value = this.channel || "";

    let uid = this.uid;
    if (!value) {
      wx.showToast({
        title: '请提供一个有效的房间名',
        icon: 'none',
        duration: 2000
      })
    } else {
      if(this.checkJoinLock()) {
        this.lockJoin();
        wx.showModal({
          title: '是否推流',
          content: '选择取消则作为观众加入，观众模式不推流',
          showCancel: true,
          success: function (res) {
            let role = "audience";
            if (res.confirm) {
              role = "broadcaster";
            }
            wx.navigateTo({
              url: `../meeting/meeting?channel=${value}&uid=${uid}&role=${role}`
            });
          }
        })
      }
    }
  },
  onInputChannel: function (e) {
    let value = e.detail.value;
    this.channel = value;
  },
})
